package com.dingding.gmall.cart.interceptor;

import com.dingding.gmall.cart.dto.UserInfoDTO;
import com.dingding.gmall.common.constant.AuthServerConstant;
import com.dingding.gmall.common.constant.CartServerConstant;
import com.dingding.gmall.common.dto.MemberDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author liudingding
 * @ClassName CartInterceptor
 * @description
 * 在执行目标方法之前，判断用户的登录状态。并封装给controller
 * @date 2021/7/29 11:07 下午
 */

@Component
public class  CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoDTO> threadLocal = new ThreadLocal<>();

    /**
     * 业务执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        MemberDTO memberDTO = null;
        if (session != null) {
            memberDTO = (MemberDTO) session.getAttribute(AuthServerConstant.LOGIN_USER);
            if (memberDTO != null) {
                //如果已登录
                userInfoDTO.setUserId(memberDTO.getId());
            }
            //如果携带了临时用户信息 - 设置为true
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0){
                for (Cookie cookie : cookies){
                    if (StringUtils.equals(cookie.getName(), CartServerConstant.TEMP_COOKIE_USER_NAME)){
                        userInfoDTO.setUserKey(cookie.getValue());
                        userInfoDTO.setTempUser(true);
                    }
                }
            }
        }
        //如果没有临时用户一定分配一个临时用户key
        if (StringUtils.isEmpty(userInfoDTO.getUserKey())) {
            userInfoDTO.setUserKey(UUID.randomUUID().toString());
        }
        if (memberDTO != null) {
            //如果已登录
            userInfoDTO.setTempUser(false);
        }
        threadLocal.set(userInfoDTO);
        return true;
    }

    /**
     * 业务执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoDTO userInfoDTO = threadLocal.get();
        //为临时用户封装cookie信息
        if (!userInfoDTO.getTempUser()) {
            Cookie cookie = new Cookie(CartServerConstant.TEMP_COOKIE_USER_NAME, userInfoDTO.getUserKey());
            // TODO 作用域 -> 以后修改为域名
            cookie.setDomain("127.0.0.1");
            cookie.setMaxAge(CartServerConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
